package com.vshop.timingtask;

import com.alibaba.fastjson.JSON;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.comentity.PartnerAccessRequestRecord;
import com.vshop.entity.comentity.UserOrderPackage;
import com.vshop.entity.interfacerequest.resultsynchronization.request.RequestChannelResultSynchronizationData;
import com.vshop.entity.interfacerequest.resultsynchronization.request.RequestChannelResultSynchronizationTradeData;
import com.vshop.entity.interfacerequest.resultsynchronization.request.RequesteChannelResultSynchronization;
import com.vshop.entity.interfacerequest.resultsynchronization.response.ResponseChannelResultSynchronization;
import com.vshop.service.PartnerAccessRequestRecordService;
import com.vshop.service.PartnerPackageService;
import com.vshop.service.SequenceService;
import com.vshop.service.UserOrderPackageService;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/***
 * 旧的，旧的，旧的：：：
 *
 * 帮企业同步支付数据接口 :目前只有大阳在用
 *
 * @author lm
 * @date 2020/1/7
 */
@Configuration
@EnableScheduling
@Api(description = "帮企业同步支付数据接口")
@Slf4j
public class ChannelResultSynchronizationTask {
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UserOrderPackageService orderPackageService;
    @Autowired
    PartnerAccessRequestRecordService accessService;
    @Autowired
    private PartnerPackageService partnerPackageService;

    /**
     * 在大阳新接口上线之前先用此任务回调给大阳
     * <p>
     * 由原来的数据表：user_order_package_t变成service_plan_order_record_t
     *
     * @author lm
     * @date 2020/10/28 14:00
     */

    @Scheduled(cron = "0/5 * * * * ?")
    @Async
    public void execute() {
        if (autoTask) {
            synchronizationTask();
        }
    }

    public void synchronizationTask() {

        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String curTime = df.format(new Date());
            // 1，生成流水号
            String connSeqNo = sequenceService.getPackageTaskNo();

            //1,去数据库查询一下有哪些记录是需要批量回传支付结果通知的
            List<UserOrderPackage> userList = orderPackageService.getChannelResultList();

            if (null == userList || userList.isEmpty()) {
                return;
            } else {
                for (UserOrderPackage userOrder : userList) {

                    String partnerCode = userOrder.getPartnerCode();

                    if (StringUtils.isNotBlank(partnerCode)) {

                        String packageCode = userOrder.getPackageCode();
                        String packageNameAS = partnerPackageService.queryPackageNameAs(partnerCode, packageCode);
                        String orderId = userOrder.getOrderId();
                        String deviceId = userOrder.getDeviceCode();
                        String payType = userOrder.getPayType();
                        String payAmount = userOrder.getPayAmount();
                        String payCurrency = userOrder.getPayCurrency();
                        String payRst = userOrder.getPayRst();
                        String requestOrderId = userOrder.getRequestOrderId();

                        List<PartnerAccessRequestRecord> accessList = accessService.queryURL(requestOrderId, deviceId);

                        if (accessList != null && !accessList.isEmpty()) {

                            for (PartnerAccessRequestRecord access : accessList) {

                                String url = access.getNotyfy_URL();
                                String token = access.getToken();
                                String deviceType = access.getDeviceType();

                                //现在数据都准备齐了，可以开始同步了
                                RequestChannelResultSynchronizationTradeData tradeData = new RequestChannelResultSynchronizationTradeData();
                                tradeData.setDeviceId(deviceId);
                                tradeData.setDeviceType(deviceType);
                                tradeData.setRequestOrderId(requestOrderId);
                                tradeData.setPackageName(packageNameAS);
                                tradeData.setOrderId(orderId);
                                tradeData.setPayType(payType);
                                tradeData.setPayAmount(payAmount);
                                tradeData.setPayCurrency(payCurrency);
                                tradeData.setPayRst(payRst);

                                RequestChannelResultSynchronizationData data = new RequestChannelResultSynchronizationData();
                                data.setConnSeqNo(connSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setToken(token);
                                data.setTradeTime(curTime);
                                data.setTradeData(tradeData);

                                RequesteChannelResultSynchronization result = new RequesteChannelResultSynchronization();
                                result.setData(data);
                                result.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                // 返回给调用者的报文
                                String jsonString = JSON.toJSONString(result);
                                log.info("【synchronizationTask】请求回调：" + jsonString);

                                // 发送post请求，并接收返回结果
                                String returnStr = HttpUtil.httpPost(url, jsonString);
                                log.info("url=" + url);

                                log.info("【synchronizationTask】响应回调：" + returnStr);
                                String str = returnStr.substring(0, 1);

                                if (str.equals("{")) {

                                    ResponseChannelResultSynchronization response = JSON.parseObject(returnStr, ResponseChannelResultSynchronization.class);

                                    if (response != null) {
                                        int tradeRstCode = response.getData().getTradeRstCode();

                                        String tradeRstMessage = response.getData().getTradeRstMessage();

                                        if (tradeRstCode != 1000 && !"success".equalsIgnoreCase(tradeRstMessage)) {
                                            //如果返回的结果不是1000，就不是成功！
                                            log.info("【synchronizationTask】同步结果返回有误");
                                            continue;
                                        } else {

                                            // 所有的通知结束之后，将数据库里面的isChannelNotity变成0，即为不需要再次通知
                                            //原来数据表：user_order_package_t更新的代码删掉了
                                            //在大阳新接口上线之前先用这种方式回调

                                            ServicePlanOrderRecord re = new ServicePlanOrderRecord();
                                            re.setIsPartnerNotice("0");
                                            re.setOrderId(orderId);
                                            re.setRequestOrderId(requestOrderId);
                                            re.setPartnerCode(partnerCode);
                                            orderPackageService.updateyIsPartnerNotity(re);

                                            log.info(orderId + "：支付结果同步成功，并成功获得客户的返回！");

                                        }
                                    } else {
                                        continue;
                                    }

                                } else {
                                    continue;

                                }

                            }

                        } else {
                            continue;
                        }

                    } else {
                        continue;
                    }
                }
            }


        } catch (Exception e) {
            log.info("【synchronizationTask】同步结果异常：" + e);
        }
    }
}
